<template>
  <div class="dashboard">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon global-config">
              <el-icon><Setting /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ stats.totalConfigs || 0 }}</h3>
              <p>全局配置</p>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon active-config">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ stats.activeConfigs || 0 }}</h3>
              <p>激活配置</p>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total-accounts">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ stats.totalAccounts || 0 }}</h3>
              <p>总账号数</p>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon account-configs">
              <el-icon><Files /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ stats.totalAccountConfigs || 0 }}</h3>
              <p>账号配置</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 账号进度 & 快捷操作 -->
    <el-row :gutter="20" class="progress-row">
      <el-col :span="18">
        <el-card class="account-progress-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>账号交易进度</span>
            </div>
          </template>

          <el-table
            :data="accountProgress"
            size="small"
            v-loading="loadingAccountProgress"
            class="progress-table"
            empty-text="暂无账号数据">
            <el-table-column prop="accountName" label="账号" min-width="140">
              <template #default="{ row }">
                <div class="account-cell">
                  <el-icon><User /></el-icon>
                  <span>{{ row.accountName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="90">
              <template #default="{ row }">
                <el-tag :type="row.accountStatus === 1 ? 'success' : 'info'">
                  {{ row.accountStatus === 1 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="targetAmount" label="今日目标" min-width="110">
              <template #default="{ row }">
                {{ formatAmount(row.targetAmount) }}
              </template>
            </el-table-column>
            <el-table-column prop="actualAmount" label="已完成" min-width="110">
              <template #default="{ row }">
                {{ formatAmount(row.actualAmount) }}
              </template>
            </el-table-column>
            <el-table-column prop="slippage" label="磨损" min-width="110">
              <template #default="{ row }">
                {{ formatAmount(row.slippage) }}
              </template>
            </el-table-column>
            <el-table-column label="完成进度" min-width="230">
              <template #default="{ row }">
                <div class="progress-cell">
                  <el-progress
                    :percentage="calcProgressPercent(row.progressRate)"
                    :status="row.progressRate >= 1 ? 'success' : 'active'"
                    :show-text="false"
                    :stroke-width="16" />
                  <span class="progress-text">{{ formatProgress(row.progressRate) }}</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="6" class="side-panel">
        <el-card class="quick-actions-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>快捷操作</span>
            </div>
          </template>

          <div class="actions-grid compact">
            <div class="action-item" @click="$router.push('/configs')">
              <el-icon><Setting /></el-icon>
              <span>全局配置</span>
            </div>
            <div class="action-item" @click="$router.push('/accounts')">
              <el-icon><User /></el-icon>
              <span>账号管理</span>
            </div>
            <div class="action-item" @click="handleViewEffectiveConfigs">
              <el-icon><View /></el-icon>
              <span>有效配置</span>
            </div>
          </div>

          <el-button class="toggle-operations" type="primary" link @click="toggleRecentOperations">
            <el-icon><View /></el-icon>
            {{ showRecentOperations ? '隐藏最近操作' : '查看最近操作' }}
          </el-button>
        </el-card>

        <transition name="fade">
          <el-card v-show="showRecentOperations" class="recent-operations-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>最近操作</span>
              </div>
            </template>

            <el-empty v-if="!recentOperations.length" description="暂无操作记录" />
            <el-timeline v-else>
              <el-timeline-item
                v-for="item in recentOperations"
                :key="item.id"
                :timestamp="formatDateTime(item.createdAt)"
                placement="top">
                <div class="operation-item">
                  <strong>{{ formatOperation(item.operationType) }}</strong>
                  <p>{{ item.description }}</p>
                </div>
              </el-timeline-item>
            </el-timeline>
          </el-card>
        </transition>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="trade-stats-row">
      <el-col :span="8">
        <el-card class="trade-stat-card">
          <div class="stat-title">今日目标交易额</div>
          <div class="stat-value">{{ formatAmount(stats.todayPlannedAmount) }}</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="trade-stat-card">
          <div class="stat-title">今日已完成交易额</div>
          <div class="stat-value">{{ formatAmount(stats.todayActualAmount) }}</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="trade-stat-card">
          <div class="stat-title">今日交易磨损</div>
          <div class="stat-value">{{ formatAmount(stats.todaySlippage) }}</div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="trade-history-row">
      <el-col :span="24">
        <el-card>
          <template #header>
            <span>最近交易统计</span>
          </template>
          <el-table :data="dailyStats" size="small" v-loading="loadingTradeStats">
            <el-table-column prop="tradeDate" label="日期" width="120">
              <template #default="{ row }">
                {{ formatDate(row.tradeDate) }}
              </template>
            </el-table-column>
            <el-table-column prop="plannedAmount" label="目标交易额">
              <template #default="{ row }">
                {{ formatAmount(row.plannedAmount) }}
              </template>
            </el-table-column>
            <el-table-column prop="actualAmount" label="已完成交易额">
              <template #default="{ row }">
                {{ formatAmount(row.actualAmount) }}
              </template>
            </el-table-column>
            <el-table-column prop="slippage" label="交易磨损">
              <template #default="{ row }">
                {{ formatAmount(row.slippage) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { http } from '@/utils/request'

const router = useRouter()

// 统计数据
const stats = reactive({
  totalConfigs: 0,
  activeConfigs: 0,
  totalAccounts: 0,
  activeAccounts: 0,
  totalAccountConfigs: 0,
  activeAccountConfigs: 0,
  recentOperations: 0,
  lastUpdateTime: '',
  todayPlannedAmount: 0,
  todayActualAmount: 0,
  todaySlippage: 0
})

const loading = ref(false)
const recentOperations = ref([])
const dailyStats = ref([])
const loadingTradeStats = ref(false)
const accountProgress = ref([])
const loadingAccountProgress = ref(false)
const showRecentOperations = ref(false)

// 初始化
onMounted(() => {
  loadDashboard()
})

const loadDashboard = async () => {
  loading.value = true
  loadingAccountProgress.value = true
  try {
    const [overview, progress] = await Promise.all([
      http.get('/stats/overview'),
      http.get('/stats/account-progress')
    ])

    Object.assign(stats, overview.data)
    accountProgress.value = (progress.data || []).sort((a, b) => (b.targetAmount || 0) - (a.targetAmount || 0))

    const operations = await http.get('/stats/recent-operations', { limit: 10 })
    recentOperations.value = operations.data || []

    await loadDailyTradeStats()
  } catch (error) {
    ElMessage.error('加载仪表盘数据失败')
  } finally {
    loading.value = false
    loadingAccountProgress.value = false
  }
}

const loadDailyTradeStats = async () => {
  loadingTradeStats.value = true
  try {
    const endDate = new Date()
    const startDate = new Date()
    startDate.setDate(endDate.getDate() - 6)
    const formatDateParam = (date) => date.toISOString().slice(0, 10)
    const response = await http.get('/stats/trade/daily', {
      startDate: formatDateParam(startDate),
      endDate: formatDateParam(endDate)
    })
    dailyStats.value = response.data || []
  } catch (error) {
    ElMessage.error('加载交易统计失败')
  } finally {
    loadingTradeStats.value = false
  }
}

// 快捷操作
const handleViewEffectiveConfigs = () => {
  router.push('/accounts')
}

const toggleRecentOperations = () => {
  showRecentOperations.value = !showRecentOperations.value
}

const formatAmount = (amount) => {
  if (amount === null || amount === undefined) return '0'
  return Number(amount).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

const calcProgressPercent = (rate) => {
  const percent = Number(rate || 0) * 100
  if (!isFinite(percent)) return 0
  return Math.max(0, Math.min(100, Number(percent.toFixed(2))))
}

const formatProgress = (rate) => `${calcProgressPercent(rate).toFixed(1)}%`

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

const formatOperation = (operationType) => {
  if (!operationType) return '操作记录'
  return operationType.replace(/_/g, ' ')
}
</script>

<style lang="scss" scoped>
.dashboard {
  .stats-row {
    margin-bottom: 20px;

    .stat-card {
      .stat-content {
        display: flex;
        align-items: center;
        padding: 10px 0;

        .stat-icon {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 20px;

          .el-icon {
            font-size: 24px;
            color: #fff;
          }

          &.global-config {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          }

          &.active-config {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
          }

          &.total-accounts {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
          }

          &.account-configs {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
          }
        }

        .stat-info {
          flex: 1;

          h3 {
            margin: 0 0 5px;
            font-size: 28px;
            font-weight: 600;
            color: #303133;
          }

          p {
            margin: 0;
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }
  }

  .progress-row {
    margin-bottom: 20px;

    .account-progress-card {
      .card-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }

      .progress-table {
        .account-cell {
          display: flex;
          align-items: center;
          gap: 8px;

          .el-icon {
            color: #409eff;
          }
        }

        .progress-cell {
          display: flex;
          align-items: center;
          gap: 12px;
          padding-right: 16px;

          .el-progress {
            flex: 1;
          }

          .progress-text {
            min-width: 60px;
            text-align: right;
            font-size: 13px;
            color: #606266;
          }
        }
      }
    }

    .side-panel {
      display: flex;
      flex-direction: column;
      gap: 20px;

      .quick-actions-card {
        .actions-grid {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 12px;
          padding: 8px 0 4px;

          &.compact .action-item {
            padding: 16px 12px;
          }

          .action-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            background: #f5f7fa;
            border-radius: 8px;
            cursor: pointer;
            transition: background 0.2s ease;

            &:hover {
              background: #ebeef5;
            }

            .el-icon {
              font-size: 24px;
              color: #409eff;
              margin-bottom: 6px;
            }

            span {
              font-size: 13px;
              color: #303133;
            }
          }
        }

        .toggle-operations {
          margin-top: 8px;
          padding: 0;
          display: flex;
          align-items: center;
          gap: 6px;
        }
      }

      .recent-operations-card {
        .operation-item {
          margin: 0;

          p {
            margin: 4px 0 0;
            color: #606266;
            font-size: 13px;
          }
        }
      }
    }
  }

  .fade-enter-active,
  .fade-leave-active {
    transition: opacity 0.2s ease;
  }

  .fade-enter-from,
  .fade-leave-to {
    opacity: 0;
  }
}
</style>
